package cn.geminis.crypto.cert.service.service;

import cn.geminis.crypto.cert.service.utils.LdapUtils;
import cn.geminis.crypto.core.x509.Crl;
import cn.geminis.crypto.core.x509.X509Certificate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import java.util.Date;

/**
 * @author puddi
 */
public class LdapService {

    public enum CertType {
        /**
         * 签名证书
         */
        Sign,

        /**
         * 加密证书
         */
        Enc
    }

    @Autowired
    private LdapTemplate ldapTemplate;

    public void publishUserCert(X509Certificate cert, CertType type) {
        LdapUtils.createPath(this.ldapTemplate, cert.getSubject());

        var attributes = new BasicAttributes();
        attributes.put(new BasicAttribute("qhUser"));
        if (CertType.Sign.equals(type)) {
            attributes.put("userCertificate", cert.getEncode());
            attributes.put("serialNumber", cert.getSerialNumber());
            attributes.put("notAfter", cert.getNotAfter());
        } else {
            attributes.put("EncryptUserCertificate", cert.getEncode());
            attributes.put("EncryptSerialNumber", cert.getSerialNumber());
            attributes.put("EncryptNotAfter", cert.getNotAfter());
        }
        attributes.put("PublishTime", new Date());

        ldapTemplate.bind(cert.getSubject(), null, attributes);
    }

    public void publishCaCert(X509Certificate cert) {
        LdapUtils.createPath(this.ldapTemplate, cert.getSubject());

        var attributes = new BasicAttributes();
        attributes.put(new BasicAttribute("pkiCA"));
        attributes.put("cACertificate", cert.getEncode());

        ldapTemplate.bind(cert.getSubject(), null, attributes);
    }

    public void publishCrl(Crl crl) {
        LdapUtils.createPath(this.ldapTemplate, crl.getIssuer());

        var attributes = new BasicAttributes();
        attributes.put(new BasicAttribute("pkiCA"));
        attributes.put("certificateRevocationList", crl.getData());

        ldapTemplate.bind(crl.getIssuer(), null, attributes);
    }

    public void publishArl(Crl arl) {
        LdapUtils.createPath(this.ldapTemplate, arl.getIssuer());

        var attributes = new BasicAttributes();
        attributes.put(new BasicAttribute("pkiCA"));
        attributes.put("authorityRevocationList", arl.getData());

        ldapTemplate.bind(arl.getIssuer(), null, attributes);
    }

}
